package com.emm.yixun.website.listeners;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.enums.ResponseEnums;
import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.*;
import com.emm.yixun.customer.service.channel.ChannelSendHttpMessageService;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.MortgageRecordServiceFacade;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.RoomChangeHistoryServiceFacade;
import com.emm.yixun.system.service.notice.signed.SignedNoticeFacade;
import com.emm.yixun.website.common.utils.SpringWebContextUtil;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.pmo.LevelProjectDataService;
import com.emm.yixun.website.service.pmo.PmoPushService;
import com.emm.yixun.website.service.system.log.ActCommitLogService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SignedListeners implements Serializable, ExecutionListener {
	private static final long serialVersionUID = 4995605219601432269L;
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public void notify(DelegateExecution execution) throws Exception {
		String id = execution.getProcessBusinessKey();
		String processInstanceId = execution.getProcessInstanceId();
		SignedServiceFacade signedServiceFacade = getSignedServiceFacade();
		ProjectRoomServiceFacade projectRoomServiceFacade = getProjectRoomServiceFacade();
		PayDepositServiceFacade payDepositServiceFacade = getPayDepositServiceFacade();
		SubscribeServiceFacade subscribeServiceFacade = getSubscribeServiceFacade();
		NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade = getNeedReceiveRefundServiceFacade();
		Response<Signed> signedResponse = signedServiceFacade.findById(Long.valueOf(id));
		if (!signedResponse.isSuccess()) {
			throw new Exception("签约记录不存在");
		}
		Signed signed = signedResponse.getEntity();
		if (null == signed) {
			throw new Exception("签约记录不存在");
		}
		if (getActivitiProcessServiceImpl().isCheckPass(processInstanceId)) {
			/**
			 * 前置判断: 防止重复提交
			 */
			boolean flag = checkAuditCommit(signed);
			if (!flag) {
				throw new Exception(ResponseEnums.RESPONSEENUMS_999999.getName());
			}

			/**
			 * 1.修改认购记录审核状态为通过 2.记录房源变更记录 3.记录应收款 4.内部转账(认筹、认购已收款转签约已收) 5.生成按揭记录
			 * 6.更改客户交易状态为认筹，判断是否多套交易并更新状态 7.推送消息
			 */
			// 1.修改认筹记录审核状态为通过
			SignedDto updateDto = new SignedDto();
			updateDto.setId(Long.valueOf(id));
			updateDto.setAuditStatus(AuditStatusEnum.SUCCESS.getNo());
			updateDto.setCheckDate(new Date());
			signedServiceFacade.updateByPrimaryKey(updateDto, true);

			if (signed.getSubscribeId() != null && !signed.getSubscribeId().equals("")) {
				SubscribeDto subscribeDto = new SubscribeDto();
				subscribeDto.setBusinessStatus("2");// 认购转签约
				subscribeDto.setId(signed.getSubscribeId());
				subscribeServiceFacade.updateByPrimaryKey(subscribeDto, true);
			} else if (signed.getPayDepositId() != null && !signed.getPayDepositId().equals("")) {
				PayDepositDto payDepositDto = new PayDepositDto();
				payDepositDto.setBusinessStatus("3");// 认筹转签约
				payDepositDto.setId(signed.getPayDepositId());
				payDepositServiceFacade.updateByPrimaryKey(payDepositDto, true);
			}

			// 2.记录房源变更记录
			RoomChangeHistoryDto dto = new RoomChangeHistoryDto();
			dto.setRoomId(signed.getRoomId());
			dto.setBusinessDynamics("签约");
			dto.setRemark("房源由【可售】转为【签约】");
			if (signed.getSubscribeId() != null && !signed.getSubscribeId().equals("")) {
				dto.setRemark("房源由【认购】转为【签约】");
			} else if (signed.getPayDepositId() != null && !signed.getPayDepositId().equals("")) {
				dto.setRemark("房源由【小定】转为【签约】");
			}
			dto.setBusinessHref("/customer/signed/toView?id=" + signed.getId() + "&returnUrl=,marketing,room,index");
			dto.setMerchantId(signed.getMerchantId());
			dto.setAccessCode(signed.getAccessCode());
			dto.setCreateUserId(signed.getCreateUserId());
			dto.setUserCode(signed.getUserCode());
			dto.setDelFlag("0");
			dto.setUpdateUserId(signed.getUpdateUserId());
			dto.setUpdateTime(new Date());
			Response<RoomChangeHistoryDto> rchSaveResponse = getRoomChangeHistoryServiceFacade().save(dto);
			if (!rchSaveResponse.isSuccess()) {
				throw new Exception(rchSaveResponse.getResultMessage());
			}
			/*
			 * ym：记录应收款
			 */
			saveNeedReceive(signed, needReceiveRefundServiceFacade);
			/*
			 * ym：记录应收款
			 */

			// 3.查询签约应收并生成按揭记录
			NeedReceiveRefundDto needReceiveRefundDto = new NeedReceiveRefundDto();
			needReceiveRefundDto.setDocType("0");
			needReceiveRefundDto.setBusinessType("2");
			needReceiveRefundDto.setRelationId(signed.getId());
			ResponseList<NeedReceiveRefund> responseList = needReceiveRefundServiceFacade
					.findByDto(needReceiveRefundDto);
			if (null != responseList && responseList.isSuccess() && null != responseList.getEntity()) {
				/*
				 * ym：内部转账
				 */
				conversionHaveReceive(signed, responseList.getEntity(), subscribeServiceFacade);
				/*
				 * ym：内部转账
				 */

				MortgageRecordServiceFacade mortgageRecordServiceFacade = getMortgageRecordServiceFacade();
				CustomerServiceFacade customerServiceFacade = getCustomerServiceFacade();
				for (NeedReceiveRefund nff : responseList.getEntity()) {
					if (nff.getPaymentMethod().equals(PaymentMethodEnum.LUMP_SUM.getNo())
							|| nff.getPaymentMethod().equals(PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo())) {
						continue;
					}
					String housingFundTyp = nff.getHousingFundType();
					if (housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_10.getNo())
							|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_17.getNo())
							|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_6.getNo())) {
						continue;
					}
					MortgageRecordDto mortgageRecordDto = new MortgageRecordDto();
					mortgageRecordDto.setNeedId(nff.getId());
					mortgageRecordDto.setSignedId(signed.getId());
					mortgageRecordDto.setRoomId(signed.getRoomId());
					mortgageRecordDto.setCustomerId(signed.getCustomerId());
					mortgageRecordDto.setProjectId(signed.getProjectId());
					mortgageRecordDto.setBusinessFlag(nff.getBusinessFlag());
					mortgageRecordDto.setHousingFundType(nff.getHousingFundType());
					Response<ProjectRoom> projectRoom = projectRoomServiceFacade.findById(signed.getRoomId());
					if (projectRoom.isSuccess() && null != projectRoom.getEntity()) {
						mortgageRecordDto.setRoomName(projectRoom.getEntity().getCombinedName());
					} else {
						mortgageRecordDto.setRoomName("未知");
					}
					Response<Customer> customerResponse = customerServiceFacade.findById(signed.getCustomerId());
					if (customerResponse.isSuccess() && null != customerResponse.getEntity()) {
						mortgageRecordDto.setCustomerName(customerResponse.getEntity().getCustomerName());
					} else {
						mortgageRecordDto.setCustomerName("未知");
					}

					mortgageRecordDto.setSignedDate(signed.getDidTime());
					mortgageRecordDto.setSignAmount(signed.getSignAmount());
					// 按揭金额
					mortgageRecordDto.setMortgageAmount(nff.getTotalReceivablesAmount());
					mortgageRecordDto.setMortgageReceivedStatus("0");
					mortgageRecordDto.setMortgageCheckStatus("0");
					mortgageRecordDto.setProcessStatus("0");

					mortgageRecordDto.setMerchantId(signed.getMerchantId());
					mortgageRecordDto.setAccessCode(signed.getAccessCode());
					mortgageRecordDto.setCreateUserId(signed.getCreateUserId());
					mortgageRecordDto.setUserCode(signed.getUserCode());
					mortgageRecordDto.setDelFlag("0");
					mortgageRecordDto.setUpdateUserId(signed.getUpdateUserId());
					mortgageRecordDto.setUpdateTime(new Date());
					mortgageRecordDto.setReceivablesFunds(nff.getReceivablesFunds());
					Response<MortgageRecordDto> response = mortgageRecordServiceFacade.save(mortgageRecordDto);
					if (!response.isSuccess()) {
						throw new Exception(response.getResultMessage());
					}
				}
			}

			/**
			 * 4.更改客户交易状态为认购，判断是否多套交易并更新状态 todo
			 * 
			 * @param bugType
			 *            业务类型： 1 认筹、2 认购、3 签约
			 * @param busId
			 *            对应业务类型Id
			 * @param customerId
			 *            客户Id
			 * @param userId
			 *            用户Id
			 */
			payDepositServiceFacade.getCustomerEntity("3", Long.valueOf(id), signed.getCustomerId(),
					signed.getUpdateUserId());

			CustomerServiceFacade customerServiceFacade = getCustomerServiceFacade();
			customerServiceFacade.changeCustomerLevel(signed.getCustomerId(), null);
			try {
				/**
				 * （签约审核通过）推送消息到app
				 * 
				 * @author ny
				 * @param param
				 *            noticeType 提醒类型, noticeBusinessId 业务主键Id
				 * @return 【${auditStatus}】房号：${roomName}；客户：${customer};
				 */
				NoticeEntity noticeEntity = new NoticeEntity();
				noticeEntity.setNoticeBusinessId(signed.getId());
				noticeEntity.setNoticeType("6");
				noticeEntity.setProcessInstanceId(processInstanceId);
				getSignedNoticeFacade().createSignedNotice(noticeEntity);

				/**
				 * 推送到渠道
				 */
				getChannelSendHttpMessageService().sendTransaction(signed.getId(), TransTypeEnum.SIGNED.getNo(), false);
				getSubscribeTransServiceFacade().signedTransfer(signed.getId());

				//添加推送PMO待推送记录
				String pmoProjectCode = getLevelProjectDataService().getProjectPmoCode(signed.getProjectId());
				String pushMonth = DateUtils.formatDate(new Date(), DateStyle.YYYYMM.getValue());
				PmoPushService pmoPushService = getPmoPushService();
				pmoPushService.addPmoPushData(signed.getProjectId(), pmoProjectCode, pushMonth, processInstanceId, "签约");

			} catch (Exception e) {
				logger.error("签约审批推送数据失败", e);
			}
		} else {
			boolean flag = checkAuditCommit(signed);
			if (!flag) {
				throw new Exception(ResponseEnums.RESPONSEENUMS_999999.getName());
			}

			/**
			 * 1.修改签约记录审核状态为不通过 2.修改房源状态为未售或者认筹
			 */

			SignedDto updateDto = new SignedDto();
			updateDto.setId(signed.getId());
			updateDto.setAuditStatus(AuditStatusEnum.REJECT.getNo());
			updateDto.setCheckDate(new Date());
			signedServiceFacade.updateByPrimaryKey(updateDto, true);

			// 认购转签约：判断认购ID是否存在，存在情况下，判断该房间是否还有认购记录，有则房间状态回到认购，否则回到可售状态，不存在情况下，往下判断
			if (signed.getSubscribeId() != null && !signed.getSubscribeId().equals("")) {
				SubscribeDto subscribeDto = new SubscribeDto();
				subscribeDto.setM_auditStatus(" and t.audit_status in (1,3)");
				subscribeDto.setRoomId(signed.getRoomId());
				ResponseList<Subscribe> responseList = subscribeServiceFacade.findByDtoJ(subscribeDto);
				if (responseList.getEntity() == null || responseList.getEntity().size() == 0) {
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(signed.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());// 可售
					Response<Integer> responseRoomDto = getProjectRoomServiceFacade().updateByPrimaryKey(projectRoomDto,
							true);
					if (!responseRoomDto.isSuccess()) {
						throw new Exception("房间状态为可售出错");
					}
				} else {
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(signed.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.BUY.getNo());// 认购
					Response<Integer> responseRoomDto = getProjectRoomServiceFacade().updateByPrimaryKey(projectRoomDto,
							true);
					if (!responseRoomDto.isSuccess()) {
						throw new Exception("房间状态为认购出错");
					}
				}
			} else if (signed.getPayDepositId() != null && !signed.getPayDepositId().equals("")) {
				// 认筹转签约：判断认筹ID是否存在，存在情况下，判断该房间是否还有认筹记录，有则房间状态回到认筹，否则回到可售状态，不存在情况下，往下判断
				PayDepositDto payDepositDto = new PayDepositDto();
				payDepositDto.setM_auditStatus(" and t.audit_status in (1,3)");
				payDepositDto.setRoomId(signed.getRoomId());
				ResponseList<PayDeposit> responseList = payDepositServiceFacade.findByDtoJ(payDepositDto);
				if (responseList.getEntity() == null || responseList.getEntity().size() == 0) {
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(signed.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());// 可售
					Response<Integer> responseRoomDto = getProjectRoomServiceFacade().updateByPrimaryKey(projectRoomDto,
							true);
					if (!responseRoomDto.isSuccess()) {
						throw new Exception("房间状态为可售出错");
					}
				} else {
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(signed.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.RESERVE.getNo());// 认筹
					Response<Integer> responseRoomDto = getProjectRoomServiceFacade().updateByPrimaryKey(projectRoomDto,
							true);
					if (!responseRoomDto.isSuccess()) {
						throw new Exception("房间状态为认筹出错");
					}
				}
			}
			// 直接签约：判断该房间是否还有认筹记录，有则房间状态回到认筹，否则回到可售状态
			if (signed.getSubscribeId() == null && signed.getPayDepositId() == null) {
				PayDepositDto payDepositDto = new PayDepositDto();
				payDepositDto.setM_auditStatus(" and t.audit_status in (1,3)");
				payDepositDto.setRoomId(signed.getRoomId());
				ResponseList<PayDeposit> responseList = payDepositServiceFacade.findByDtoJ(payDepositDto);
				if (responseList.getEntity() == null || responseList.getEntity().size() == 0) {
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(signed.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());// 可售
					Response<Integer> responseRoomDto = getProjectRoomServiceFacade().updateByPrimaryKey(projectRoomDto,
							true);
					if (!responseRoomDto.isSuccess()) {
						throw new Exception("房间状态为可售出错");
					}
				} else {
					ProjectRoomDto projectRoomDto = new ProjectRoomDto();
					projectRoomDto.setId(signed.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.RESERVE.getNo());// 认筹
					Response<Integer> responseRoomDto = getProjectRoomServiceFacade().updateByPrimaryKey(projectRoomDto,
							true);
					if (!responseRoomDto.isSuccess()) {
						throw new Exception("房间状态为认筹出错");
					}
				}
			}

			/**
			 * （签约审核不通过）推送消息到app
			 * 
			 * @author ny
			 * @param param
			 *            noticeType 提醒类型, noticeBusinessId 业务主键Id
			 * @return 【${auditStatus}】房号：${roomName}；客户：${customer};
			 */
			NoticeEntity noticeEntity = new NoticeEntity();
			noticeEntity.setNoticeBusinessId(signed.getId());
			noticeEntity.setNoticeType("6");
			noticeEntity.setProcessInstanceId(processInstanceId);
			getSignedNoticeFacade().createSignedNotice(noticeEntity);

			// 删除已收记录
			/*
			 * HaveReceiveRefundServiceFacade
			 * haveReceiveRefundServiceFacade=getHaveReceiveRefundServiceFacade();
			 * HaveReceiveRefundDto dto = new HaveReceiveRefundDto();
			 * dto.setRelationId(signed.getId()); dto.setReceivablesType("2");
			 * haveReceiveRefundServiceFacade.deleteByDto(dto);
			 */
		}

	}

	private void conversionHaveReceive(Signed signed, List<NeedReceiveRefund> needList,
			SubscribeServiceFacade subscribeServiceFacade) {
		String extraInformation = signed.getExtraInformation();
		if (StringUtils.isBlank(extraInformation)) {
			return;
		}
		HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade = getHaveReceiveRefundServiceFacade();
		NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade = getNeedReceiveRefundServiceFacade();
		List<HaveReceiveRefund> convertList = new ArrayList<HaveReceiveRefund>();
		// 查询认筹已收
		// 查询认购已收
		// 绑定签约应收第一条
		if (signed.getSubscribeId() != null) {
			// 判断签约对应的认购是否存在未签约记录
			SubscribeTransDto stDto = new SubscribeTransDto();
			stDto.setSubId(signed.getSubscribeId());
			ResponseList<SubscribeTrans> stListRes = getSubscribeTransServiceFacade().findByDto(stDto);
			if (stListRes.isSuccess()) {
				List<SubscribeTrans> stList = stListRes.getEntity();
				if (null != stList && stList.size() > 0) {
					return;
				}
			}

			Response<Subscribe> subscribeResponse = subscribeServiceFacade.findById(signed.getSubscribeId());
			Subscribe subscribe = subscribeResponse.getEntity();
			// 认购转签约
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(subscribe.getId());
			// 已收
			haveReceiveRefundDto.setDocType("0");
			// 认购
			haveReceiveRefundDto.setReceivablesType("1");
			// 正常
			haveReceiveRefundDto.setTransferStatus("0");
			ResponseList<HaveReceiveRefund> responseHrrList = haveReceiveRefundServiceFacade
					.findByDto(haveReceiveRefundDto);
			List<HaveReceiveRefund> haveReceiveList = responseHrrList.getEntity();
			if (null != haveReceiveList && haveReceiveList.size() > 0) {
				for (HaveReceiveRefund have : haveReceiveList) {
					if (!have.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())) {
						convertList.add(have);
					}
				}
			}

		} else if (signed.getPayDepositId() != null) {
			// 认筹转认购
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(signed.getPayDepositId());
			// 已收
			haveReceiveRefundDto.setDocType("0");
			// 认筹
			haveReceiveRefundDto.setReceivablesType("0");
			ResponseList<HaveReceiveRefund> responseHrrList = haveReceiveRefundServiceFacade
					.findByDto(haveReceiveRefundDto);
			List<HaveReceiveRefund> haveReceiveList = responseHrrList.getEntity();
			if (null != haveReceiveList && haveReceiveList.size() > 0) {
				for (HaveReceiveRefund have : haveReceiveList) {
					if (!have.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())) {
						convertList.add(have);
					}
				}

			}
		}

		// 查找应收
		NeedReceiveRefund tempNeedReceive = null;
		for (NeedReceiveRefund nrr : needList) {
			String housingFundTyp = nrr.getHousingFundType();
			if (housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_5.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_6.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_10.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_12.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_17.getNo())) {
				tempNeedReceive = nrr;
				break;
			}
		}
		if (null != tempNeedReceive && convertList.size() > 0) {
			try {
				HaveReceiveRefund haveReceiveRefund = null;
				BigDecimal totalRealAmount = BigDecimal.ZERO;
				for (HaveReceiveRefund hrr : convertList) {
					totalRealAmount = totalRealAmount.add(hrr.getRealAmount());
					if (null == haveReceiveRefund)
						haveReceiveRefund = hrr;
				}

				// 转到应收下
				HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
				haveReceiveRefundDto = BeanUtil.convert2T(haveReceiveRefundDto, haveReceiveRefund);
				haveReceiveRefundDto.setId(null);
				haveReceiveRefundDto.setRelationId(signed.getId());
				haveReceiveRefundDto.setReceivablesType("2");
				haveReceiveRefundDto.setReceivablesId(tempNeedReceive.getId());
				haveReceiveRefundDto.setHousingFundType(tempNeedReceive.getHousingFundType());
				if (signed.getSubscribeId() != null) {
					// 认购转签约
					haveReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_13.getNo());
				} else if (signed.getPayDepositId() != null) {
					// 认筹转签约
					haveReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_12.getNo());
				}
				haveReceiveRefundDto.setTransferStatus("0");
				haveReceiveRefundDto.setBillCode("");
				haveReceiveRefundDto.setRealAmount(totalRealAmount);
				haveReceiveRefundDto.setStatementId(null);
				haveReceiveRefundDto.setStatementType(Long.valueOf(StatementTypeEnum.TRANSFER.getNo()));
				haveReceiveRefundDto.setStatementDate(new Date());
				haveReceiveRefundDto.setRemark("系统内部转账");
				haveReceiveRefundDto.setPaymentMethod(signed.getPaymentMethod());
				haveReceiveRefundDto.setCreateTime(new Date());
				Response<HaveReceiveRefundDto> hrrResponse = haveReceiveRefundServiceFacade.save(haveReceiveRefundDto);
				if (!hrrResponse.isSuccess()) {
					throw new Exception("转已收款出错");
				}

				for (HaveReceiveRefund hrr : convertList) {
					// 原记录更新为转出
					HaveReceiveRefundDto updateDto = new HaveReceiveRefundDto();
					updateDto.setId(hrr.getId());
					updateDto.setTransferStatus("1");
					Response<Integer> integerRespone = haveReceiveRefundServiceFacade.updateByPrimaryKey(updateDto,
							true);
					if (!integerRespone.isSuccess()) {
						throw new Exception("转已收款出错");
					}
				}

				// 检查代收款是否已收满
				for (NeedReceiveRefund nrr : needList) {
					BigDecimal needReceive = nrr.getTotalReceivablesAmount();
					Response<BigDecimal> haveReceiveRes = haveReceiveRefundServiceFacade.findHaveAmount(nrr.getId());
					if (haveReceiveRes.isSuccess()) {
						BigDecimal haveReceive = haveReceiveRes.getEntity();
						if (needReceive.compareTo(haveReceive) == 0) {
							NeedReceiveRefundDto nrrDto = new NeedReceiveRefundDto();
							nrrDto.setId(nrr.getId());
							nrrDto.setStatus("0");
							needReceiveRefundServiceFacade.updateByPrimaryKey(nrrDto, true);
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void saveNeedReceive(Signed signed, NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade) {
		String extraInformation = signed.getExtraInformation();
		if (StringUtils.isBlank(extraInformation)) {
			return;
		}
		JSONObject object = JSON.parseObject(extraInformation);
		JSONArray needReceive = object.getJSONArray("paymentDetails");
		if (null != needReceive && needReceive.size() > 0) {
			for (int i = 0; i < needReceive.size(); i++) {
				NeedReceiveRefundDto needReceiveRefundDto = JSONObject
						.parseObject(needReceive.getJSONObject(i).toJSONString(), NeedReceiveRefundDto.class);
				needReceiveRefundDto.setRelationId(signed.getId());
				needReceiveRefundDto.setBusinessType("2");
				needReceiveRefundDto.setCustomerId(signed.getCustomerId());
				needReceiveRefundDto.setRoomId(signed.getRoomId());
				needReceiveRefundDto.setStatus("1");
				needReceiveRefundDto.setPostponedStatus("0");
				needReceiveRefundDto.setDocType("0");
				needReceiveRefundDto.setRemark("签约收款");
				needReceiveRefundDto.setMerchantId(signed.getMerchantId());
				needReceiveRefundDto.setPaymentMethod(signed.getPaymentMethod());
				needReceiveRefundDto.setUserCode(signed.getUserCode());
				needReceiveRefundDto.setAccessCode(signed.getAccessCode());
				needReceiveRefundDto.setCreateUserId(signed.getCreateUserId());
				needReceiveRefundDto.setDelFlag("0");
				needReceiveRefundDto.setUpdateUserId(signed.getUpdateUserId());
				needReceiveRefundDto.setUpdateTime(new Date());
				Response<NeedReceiveRefundDto> nrrdSaveResponse = needReceiveRefundServiceFacade
						.save(needReceiveRefundDto);
				/*
				 * NeedReceiveRefundDto nrrdSaveResponse = needReceiveRefundService
				 * .create(needReceiveRefundDto);
				 */
				if (!nrrdSaveResponse.isSuccess()) {
					throw new RuntimeException("保存签约应收信息错误");
				}
			}
		}
	}

	/**
	 * 前置判断,审核记录是否已经提交,防止重复提交 产生原因: 提交审核,后台处理中时,刷新页面再次提交审核,会重复 true: 可继续执行 false:
	 * 不可执行
	 */
	public boolean checkAuditCommit(Signed entity) {
		// 业务数据为null时,默认通过.为了不改变老业务,不影响流程正常行走
		if (null == entity) {
			return true;
		}
		return getActcommitLogService().checkActCommit(entity.getAuditStatus(), entity.getMerchantId(), entity.getId(),
				entity.getProcInstId(), "签约", "PC");
	}

	private HaveReceiveRefundServiceFacade getHaveReceiveRefundServiceFacade() {
		return (HaveReceiveRefundServiceFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("haveReceiveRefundServiceFacade");
	}

	private SignedNoticeFacade getSignedNoticeFacade() {
		return (SignedNoticeFacade) SpringWebContextUtil.getApplicationContext().getBean("signedNoticeFacade");
	}

	private ProjectRoomServiceFacade getProjectRoomServiceFacade() {
		return (ProjectRoomServiceFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("projectRoomServiceFacade");
	}

	private SignedServiceFacade getSignedServiceFacade() {
		return (SignedServiceFacade) SpringWebContextUtil.getApplicationContext().getBean("signedServiceFacade");
	}

	private PayDepositServiceFacade getPayDepositServiceFacade() {
		return (PayDepositServiceFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("payDepositServiceFacade");
	}

	private SubscribeServiceFacade getSubscribeServiceFacade() {
		return (SubscribeServiceFacade) SpringWebContextUtil.getApplicationContext().getBean("subscribeServiceFacade");
	}

	private ActivitiProcessServiceImpl getActivitiProcessServiceImpl() {
		return (ActivitiProcessServiceImpl) SpringWebContextUtil.getApplicationContext()
				.getBean("activitiProcessServiceImpl");
	}

	private RoomChangeHistoryServiceFacade getRoomChangeHistoryServiceFacade() {
		return (RoomChangeHistoryServiceFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("roomChangeHistoryServiceFacade");
	}

	private NeedReceiveRefundServiceFacade getNeedReceiveRefundServiceFacade() {
		return (NeedReceiveRefundServiceFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("needReceiveRefundServiceFacade");
	}

	private MortgageRecordServiceFacade getMortgageRecordServiceFacade() {
		return (MortgageRecordServiceFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("mortgageRecordServiceFacade");
	}

	private CustomerServiceFacade getCustomerServiceFacade() {
		return (CustomerServiceFacade) SpringWebContextUtil.getApplicationContext().getBean("customerServiceFacade");
	}

	private ChannelSendHttpMessageService getChannelSendHttpMessageService() {
		return (ChannelSendHttpMessageService) SpringWebContextUtil.getApplicationContext()
				.getBean("channelSendHttpMessageService");
	}

	private SubscribeTransServiceFacade getSubscribeTransServiceFacade() {
		return (SubscribeTransServiceFacade) SpringWebContextUtil.getApplicationContext()
				.getBean("subscribeTransServiceFacade");
	}

	private LevelProjectDataService getLevelProjectDataService() {
		return (LevelProjectDataService) SpringWebContextUtil.getApplicationContext()
				.getBean("levelProjectDataService");
	}

	private ActCommitLogService getActcommitLogService() {
		return (ActCommitLogService) SpringWebContextUtil.getApplicationContext().getBean("actCommitLogService");
	}

	private PmoPushService getPmoPushService(){
		return (PmoPushService)SpringWebContextUtil.getApplicationContext().getBean("pmoPushService");
	}

}
